<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\know\validate;

use app\know\model\SysConfigModel;
use think\Validate;
use think\facade\Log;

class TeachingMaterialVerifyValidate extends Validate
{
    protected $rule = [
        'key' => 'require|checkKey|min:1',
        'value' => 'require|min:1|checkEditKey',
        'type' => 'require|min:1',
        'id' => 'require|gt:0',
    ];

    protected $message = [
        'key.require' => '编码为必填项',
        'key.min' => '编码不能为空',
        'value.require' => '内容为必填项',
        'value.min' => '内容不能为空',
        'type.require' => '类型为必填项',
        'type.min' => '类型不能为空',
        'id.require' => 'id不能为空',
    ];

    protected $scene = [
        'add'  => ['key', 'value' , 'type'],
        'edit' => ['id', 'value'],
        'delete' => ['id'],
    ];

    // 自定义验证规则
    // 同一类型下key不重复，value不重复
    protected function checkKey($value, $rule, $data)
    {
        $model = new SysConfigModel();
        $where = [['key', '=', $data['key']], ['value', '=', $data['value']]];
        $item  = $model->where('type', $data['type'])
                       ->where(function($query) use ($where) {$query->whereOr($where);})
                       ->find();
        Log::debug('AdminSysConfigValidate---' . $model->getLastSql());
        if (empty($item)) {
            return true;
        } else {
            return $data['key'] . "---已经存在---" . $item['value'];
        }
    }

    protected function checkEditKey($value, $rule, $data)
    {
        if ($this->currentScene != 'edit') {
            return true;
        }
        $model = new SysConfigModel();
        $where = [['key', '=', $data['key']], ['value', '=', $data['value']]];
        $item  = $model->where('type', $data['type'])
                       ->where('id', '<>', $data['id'])
                       ->where('key', $data['key'])
                       ->find();
        Log::debug('checkEditKey---' . $model->getLastSql());
        if (empty($item)) {
            return true;
        } else {
            return $data['key'] . "---已经存在---" . $item['value'];
        }
    }
}